//
//  ImageTurnPDFMode.m
//  ImageTurnPDF
//
//  Created by 向祖华 on 16/4/1.
//  Copyright © 2016年 向祖华. All rights reserved.
//
#import "ImageTurnPDFMode.h"
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
/*
 此封装模块，只需要传入三个对象
 1.图片数组，默认png格式的图片，也可以是jpeg格式的
 2.往沙盒中存储PDF文件时用的文件名字，就是一个字符串，不需要后缀
 3.用于展示的UIWebview对象
 */

@implementation ImageTurnPDFMode

//将存放image的数组中的数据转换成NSData对象
-(NSMutableArray*)getImageDataArrWithImageArr:(NSArray*)arr{
    NSMutableArray * array = [[NSMutableArray alloc] init];
    for (UIImage*image in arr) {
        //NSData*imageData = UIImageJPEGRepresentation(image, 1);
        NSData * imageData = UIImagePNGRepresentation(image);
        [array addObject:imageData];
    }
    return array;}
#pragma waring.......不太懂
//将图片的方向改变横向改 -- 纵向
-(UIImage *)imageChange:(UIImage *)image{
    long double rotate = 0.0;
    CGRect rect;
    float translateX = 0;
    float translateY = 0;
    float scaleX = 1.0;
    float scaleY = 1.0;
    
    rotate = M_PI_2;//3.14的一般
    rect = CGRectMake(0, 0, image.size.height, image.size.width);
    translateX = 0;
    translateY = -rect.size.width;
    scaleY = rect.size.width/rect.size.height;
    scaleX = rect.size.height/rect.size.width;
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    //做CTM变换
    CGContextTranslateCTM(context, 0.0, rect.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextRotateCTM(context, rotate);
    CGContextTranslateCTM(context, translateX, translateY);
    
    CGContextScaleCTM(context, scaleX, scaleY);
    //绘制图片
    CGContextDrawImage(context, CGRectMake(0, 0, rect.size.width, rect.size.height), image.CGImage);
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    
    return newPic;
}
#pragma waring.......不太懂
//图片转换成PDF文件
-(void)creatPDFWithImageArr:(NSArray *)ImageArr fileName:(NSString *)filename orientation:(ENUM_image_orientation)orientation{
    NSMutableArray * tempArr = [[NSMutableArray alloc] init];
    //判断是横向还是纵向
    if(orientation == horizontal){//如果是横向，则旋转图片
        for (int i = 0 ; i < ImageArr.count; i++) {
            [tempArr addObject:[self imageChange:ImageArr[i]]];
        }
    }
    else{
        for (int i = 0 ; i < ImageArr.count; i++) {
            [tempArr addObject:ImageArr[i]];
        }
    }
    //调用将图片数组转换成图片data的数组
    NSMutableArray * array =[self getImageDataArrWithImageArr:tempArr];
    //取到pdf文件要存放的目标地址--temp文件夹中
    NSString *pdfPath = [NSTemporaryDirectory() stringByAppendingString:[NSString stringWithFormat:@"%@.pdf",filename]];
    //创建pdf
    const char *path = [pdfPath UTF8String];
    CFStringRef pdfPathRef = CFStringCreateWithCString(NULL, path, kCFStringEncodingUTF8);
    CFURLRef PDFUrl = CFURLCreateWithFileSystemPath(NULL, pdfPathRef, kCFURLPOSIXPathStyle, NO);
    //for循环得到CFDataRef类型对象数组和CGRect类型对象的数组
    NSMutableArray *imgeDataRefArr = [NSMutableArray array];
    NSMutableArray * rectArr = [NSMutableArray array];
    CGFloat maxHeight = 0;
    for (int i = 0 ; i < array.count; i++) {
        CFDataRef imgDataRef = (__bridge CFDataRef)array[i];//获取图片的data类型
        [imgeDataRefArr addObject:(__bridge id _Nonnull)(imgDataRef)];
        UIImage *img = [UIImage imageWithData:array[i]];//获取到图片的
        //获取所有图片的放大后的高度（即pdf文件的最大高度）
        maxHeight = (kScreenWidth/img.size.width)*img.size.height + maxHeight;
        //获取改变后的单张图片的尺寸
        CGRect rect = CGRectMake(0, 0, kScreenWidth, (kScreenWidth/img.size.width)*img.size.height);
        //图片结构存储数组添加结构
        [rectArr addObject:[NSValue valueWithCGRect:rect]];
    }
    //得到一个基础大尺寸（即PDF的文件的尺寸）
    CGRect allRect = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    
    CGContextRef context = CGPDFContextCreateWithURL(PDFUrl, &allRect, NULL);//创建了一个PDF,context就相当于一个接口，后面通过这个变量来编辑PDF
    CFRelease(pdfPathRef);//需要手动释放，不会自动释放
    for (int i = 0; i < array.count; i++) {
        CGRect rect = [rectArr[i] CGRectValue];
        //编辑pdf中的内容
        CFMutableDictionaryRef pageDic = CFDictionaryCreateMutable(NULL,0,&kCFTypeDictionaryKeyCallBacks,&kCFTypeDictionaryValueCallBacks);
        CFDataRef boxData = NULL;
        boxData = CFDataCreate(NULL,(const UInt8 *)&rect, sizeof (CGRect));
        CFDictionarySetValue(pageDic, kCGPDFContextMediaBox, boxData);
        CFDataRef imgDataRef = (__bridge CFDataRef)array[i];
        CGPDFContextBeginPage(context, pageDic);//开始编辑
        //绘画
        CGDataProviderRef source = CGDataProviderCreateWithCFData(imgDataRef);
        CGImageRef image = CGImageCreateWithPNGDataProvider(source, NULL, NO, kCGRenderingIntentDefault);
        CGContextDrawImage(context, rect, image);//在这个pdf上面添加文件，rect为大小和位置，起始点左下角(0,0)
        CGPDFContextEndPage(context);//结束编辑
        //内存管理释放
        CFRelease(boxData);
        CFRelease(pageDic);
    }
    CGContextRelease(context);//如果不释放，会导致文件打不开
    CFRelease(PDFUrl);
}
//调用PDF文件展示到UIWebview上
-(void)showPDFInWebview:(UIWebView*)webView fileName:(NSString*)fileName{
    //从沙盒中取到PDF文件路径
    NSString *path = NSTemporaryDirectory();
    NSString *pdfPath = [path stringByAppendingString:[NSString stringWithFormat:@"%@.pdf",fileName]];
    NSLog(@"%@",pdfPath);
    //创建本地文件的url路径
    NSURL *url = [NSURL URLWithString:pdfPath];
    //创建网络请求
    NSURLRequest *requset = [[NSURLRequest alloc] initWithURL:url];
    //加载界面
    [webView loadRequest:requset];

}


@end
